import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:video_compress/video_compress.dart';
import 'package:video_ducafecat_flutter_v3/common/index.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// 视频播放器
/// 压缩视频，显示压缩进度
class MsgVideoCompressWidget extends StatefulWidget {
  const MsgVideoCompressWidget({
    super.key,
    this.initAsset,
    this.onCompleted,
  });

  /// 视频 asset
  final AssetEntity? initAsset;

  /// 完成压缩回调
  final Function(CompressMediaFile)? onCompleted;

  @override
  State<MsgVideoCompressWidget> createState() => _MsgVideoCompressWidgetState();
}

class _MsgVideoCompressWidgetState extends State<MsgVideoCompressWidget> {
  /// 压缩消息订阅
  Subscription? _subscription;

  /// 资源 asset
  AssetEntity? _asset;

  /// 是否载入中
  bool _isLoading = true;

  /// 是否错误
  bool _isError = false;

  /// 压缩进度
  double _progress = 0;

  @override
  void initState() {
    super.initState();
    _asset = widget.initAsset;

    // 压缩进度订阅
    _subscription = VideoCompress.compressProgress$.subscribe((progress) {
      debugPrint('progress: $progress');
      setState(() {
        _progress = progress;
      });
    });

    // 开始压缩
    if (mounted) onLoad();
  }

  /// 释放
  @override
  void dispose() {
    // 取消压缩
    VideoCompress.cancelCompression();
    // 取消订阅
    _subscription?.unsubscribe();
    _subscription = null;
    // 删除所有缓存
    VideoCompress.deleteAllCache();
    super.dispose();
  }

  /// 文件 file
  Future<File> getFile() async {
    var file = await _asset?.file;
    if (file == null) throw 'No file';
    return file;
  }

  /// 开始压缩
  void onLoad() async {
    // 1. 初始界面状态
    setState(() {
      _isLoading = _asset != null;
      _isError = _asset == null;
    });

    // 2. 安全检查, 容错
    if (_asset == null) return;

    //
    try {
      var file = await getFile();

      // 开始视频压缩
      var result = await DuCompress.video(file);

      // 异步等待完成 回调
      if (widget.onCompleted != null) widget.onCompleted!(result);
    } catch (error) {
      if (kDebugMode) {
        print(error);
      }
      Loading.toast('Video file load error.');
      setState(() {
        _isError = true;
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 主视图
  Widget _mainView() {
    // 默认空组件
    List<Widget> ws = [];

    // 视频图片
    if (_asset != null) {
      ws.add(AssetEntityImage(
        _asset!,
        fit: BoxFit.fitWidth,
        width: double.infinity,
      ));
    }

    // 错误提示
    if (_isError) {
      ws.add(
        Icon(
          Icons.error,
          size: 40,
          color: AppColors.onPrimary,
        ),
      );
    } else if (_isLoading) {
      // 进度信息
      ws.add(
        <Widget>[
          // 旋转 loading
          CircularProgressIndicator(
            strokeWidth: 2,
            color: AppColors.onPrimary,
          ).tightSize(40),

          // 进度文字
          Text(
            '${_progress.toStringAsFixed(2)}%',
            style: TextStyle(
              fontSize: 13,
              color: AppColors.onPrimary,
            ),
          ),
        ].toColumn(
          mainAxisAlignment: MainAxisAlignment.center,
        ),
      );
    }

    // 按比例组件包裹
    return AspectRatio(
      aspectRatio: 16 / 9,
      child: Container(
        color: Colors.grey[100],
        child: ws.toStack(
          alignment: Alignment.center,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _mainView();
  }
}
